﻿using BAL;
using DAL;
using DAL.DataProvider;
using DAL.DataTransferObject;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Printing;
using System.Text;
using System.Windows.Forms;

namespace Module.QLHoaDon
{
    public partial class frmQLHoaDon : Form
    {
        DataView dvSearch;

        int rowIndex;

        //In an
        int RowPerPage = 1, pageNum = 0;

        int sum = 0;
        int chietKhau = 0;
        int tienTra = 0;
        int tienKhach = 0;
        public frmQLHoaDon()
        {
            InitializeComponent();
            //this.Height = 1000;
        }

        private NhanVien passData;

        public frmQLHoaDon(NhanVien obj)
        {
            InitializeComponent();
            //MessageBox.Show(obj._account);
            this.passData = obj;
            if (obj._level < 3)
                grbThongKe.Enabled = false;
        }

        HoaDonBAO hdBAO = new HoaDonBAO();
        private void frmQLHoaDon_Load(object sender, EventArgs e)
        {
            Root.AutoScrollMinSize = new Size(0, 900);

            dvSearch = new DataView(hdBAO.SelectAllHoaDon());

            DataView dv = new DataView(hdBAO.SelectAllHoaDon());
            dgvHoaDon.DataSource = dv;
            TextboxInputVisible(false);
            ButtonVisible(true);
            ResetTextboxInput();

            int de_width = 0;
            for (int i = 0; i < dgvHoaDon.Columns.Count; i++)
                de_width += dgvHoaDon.Columns[i].Width;
            dgvHoaDon.Columns[dgvHoaDon.Columns.Count - 1].Width = this.Width - de_width;
        }

        private void dgvHangHoa_RowClicked(object sender, DataGridViewCellEventArgs e)
        {

        }



        public void GetDataFromSelectedRow(DataGridViewSelectedRowCollection row)
        {
            txtMaHD.Text = row[0].Cells[0].Value.ToString();
            txtMaKH.Text = row[0].Cells[1].Value.ToString();
            dtpkNgayIn.Value = Convert.ToDateTime(row[0].Cells[2].Value.ToString());
            dtpkNgayMua.Value = Convert.ToDateTime(row[0].Cells[3].Value.ToString());
            txtTienKhach.Text = row[0].Cells[4].Value.ToString();
            txtNVTT.Text = row[0].Cells[5].Value.ToString();
            txtMaQT.Text = row[0].Cells[6].Value.ToString();
            txtGGKhach.Text = row[0].Cells[7].Value.ToString();
        }
        public void GetDataFromRow(DataGridViewRowCollection row, int rowIndex)
        {
            if (dgvHoaDon.Rows.Count - 1 >= rowIndex)
                txtMaHD.Text = row[rowIndex].Cells[0].Value.ToString();
            else
                txtMaHD.Text = row[0].Cells[0].Value.ToString();
            txtMaKH.Text = row[0].Cells[1].Value.ToString();
            dtpkNgayIn.Value = Convert.ToDateTime(row[0].Cells[2].Value.ToString());
            dtpkNgayMua.Value = Convert.ToDateTime(row[0].Cells[3].Value.ToString());
            txtTienKhach.Text = row[0].Cells[4].Value.ToString();
            txtNVTT.Text = row[0].Cells[5].Value.ToString();
            txtMaQT.Text = row[0].Cells[6].Value.ToString();
            txtGGKhach.Text = row[0].Cells[7].Value.ToString();
        }

        private void dgvHangHoa_Click(object sender, EventArgs e)
        {
            if (searchClicked)
            {
                //if (dgvHoaDon.SelectedRows.Count >= 1)
                //{
                //    HoaDon tempHD = RowToHoaDon();
                //    DataView dvTemp = new DataView(hdBAO.SelectAllHoaDon());
                //    rowIndex = AutoGenCode.GetRealIndexOfRow(tempHD.maHoaDon, dvTemp, 0);
                //    //MessageBox.Show(txtMaHD.Text);
                //}
                ////MessageBox.Show(rowIndex.ToString());
                //btnSearch.PerformClick();
                //dgvHoaDon.ClearSelection();
                //dgvHoaDon.CurrentRow.Selected = false;
                ////dgvHoaDon.FirstDisplayedScrollingRowIndex = rowIndex;
                //dgvHoaDon.Rows[0].Selected = true;
                //dgvHoaDon.CurrentCell = dgvHoaDon[0, 0];
                //dgvHoaDon.SelectedRows[rowIndex].Selected = true;

                if (dgvHoaDon.SelectedRows.Count >= 1)
                {
                    HoaDon tempHD = RowToHoaDon();
                    DataView dvTemp = new DataView(hdBAO.SelectAllHoaDon());
                    rowIndex = AutoGenCode.GetRealIndexOfRow(tempHD.maHoaDon, dvTemp, 0);
                    GetDataFromRow(dgvHoaDon.Rows, rowIndex);
                }
                TextboxInputVisible(true);
                txtMaKH.ReadOnly = txtTienKhach.ReadOnly = false;
                txtMaQT.Enabled = false;
                btnDetailsHoaDon.Enabled = btnPrint.Enabled = btnRefreshHoaDon.Enabled = true;
            }
            else
            {
                TextboxInputVisible(true);
                txtMaHD.ReadOnly = true;
                txtGGKhach.ReadOnly = true;
                ButtonVisible(false);
                btnRefreshHoaDon.Enabled = true;
                btnPrint.Enabled = true;

                if (dgvHoaDon.SelectedRows.Count >= 1)
                {
                    GetDataFromSelectedRow(dgvHoaDon.SelectedRows);
                }
            }

        }

        public HoaDon RowToHoaDon()
        {
            HoaDon obj = new HoaDon();
            obj.maHoaDon = dgvHoaDon.SelectedRows[0].Cells[0].Value.ToString();
            obj.maKhachHang = dgvHoaDon.SelectedRows[0].Cells[1].Value.ToString();
            obj.ngayMuaHang = Convert.ToDateTime(dgvHoaDon.SelectedRows[0].Cells[2].Value.ToString());
            obj.ngayInHoaDon = Convert.ToDateTime(dgvHoaDon.SelectedRows[0].Cells[3].Value.ToString());
            obj.tienKhachDua = Convert.ToInt32(dgvHoaDon.SelectedRows[0].Cells[4].Value.ToString());
            obj.maNVThanhToan = dgvHoaDon.SelectedRows[0].Cells[5].Value.ToString();
            obj.maQT = dgvHoaDon.SelectedRows[0].Cells[6].Value.ToString();
            //obj.giamGiaKhach = dgvHoaDon.SelectedRows[0].Cells[7].Value.ToString();
            return obj;
        }


        private void dgvHangHoa_DoubleClick(object sender, EventArgs e)
        {
            HoaDon passData = RowToHoaDon();
            frmChiTietHoaDon frm = new frmChiTietHoaDon(passData);
            DialogResult result = frm.ShowDialog();
            if (result == DialogResult.OK)
                btnRefreshHoaDon.PerformClick();
        }

        private void btnDetailsHoaDon_Click(object sender, EventArgs e)
        {
            HoaDon passData = RowToHoaDon();
            frmChiTietHoaDon frm = new frmChiTietHoaDon(passData);
            DialogResult result = frm.ShowDialog();
            if (result == DialogResult.OK)
                if (!searchClicked)
                    btnRefreshHoaDon.PerformClick();
        }



        HoaDon obj;
        KhachHangBAO khBAO = new KhachHangBAO();
        NhanVienBAO nvBAO = new NhanVienBAO();
        //HoaDonDAO hdDAO = new HoaDonDAO();
        private void btnAddHoaDon_Click(object sender, EventArgs e)
        {
            obj = new HoaDon();
            bool flag = false;
            obj.maHoaDon = txtMaHD.Text;
            try
            {
                List<KhachHang> listKH = khBAO.KhachHang_GetData();
                foreach (KhachHang itemKH in listKH)
                    if (itemKH.maKhachHang == txtMaKH.Text)
                        flag = true;
                if (!flag)
                    throw new Exception("loi ma kh");
                obj.maKhachHang = txtMaKH.Text;
                flag = false;
                try
                {
                    List<NhanVien> listNV = nvBAO.GetListNhanVien();
                    foreach (NhanVien itemNV in listNV)
                        if (itemNV.maNV == txtNVTT.Text)
                            flag = true;
                    if (!flag)
                        throw new Exception("Không tồn tại mã nhân viên này !");
                    flag = false;
                    obj.maNVThanhToan = txtNVTT.Text;
                    dtpkBD.MaxDate = dtpkKT.MaxDate = DateTime.Now;
                    obj.ngayMuaHang = dtpkNgayMua.Value;
                    obj.ngayInHoaDon = dtpkNgayMua.Value;
                    obj.maQT = txtMaQT.Text;
                    try
                    {
                        obj.tienKhachDua = Convert.ToInt32(txtTienKhach.Text);
                        obj.giamGiaKhach = "0";
                        hdBAO.InsertHoaDon(obj);
                        frmChiTietHoaDon frm = new frmChiTietHoaDon(obj);
                        DialogResult result = frm.ShowDialog();
                        if (result == DialogResult.OK)
                            btnRefreshHoaDon.PerformClick();
                    }
                    catch (FormatException)
                    {
                        MessageBox.Show("Phải nhập giá trị ở ô \"Tiền Khách đưa\" !");
                        txtTienKhach.Focus();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    txtNVTT.Focus();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                txtMaKH.Focus();
            }

            dgvHoaDon.DataSource = hdBAO.SelectAllHoaDon();
        }

        private void TextboxInputVisible(bool logic)
        {
            txtGGKhach.ReadOnly = !logic;
            txtMaHD.ReadOnly = !logic;
            txtMaKH.ReadOnly = logic;
            txtMaQT.Enabled = !logic;
            //txtNVTT.ReadOnly = logic;
            txtTienKhach.ReadOnly = logic;
        }

        private void ButtonVisible(bool logic)
        {
            btnAddHoaDon.Enabled = logic;
            btnDetailsHoaDon.Enabled = !logic;
            btnPrint.Enabled = !logic;
            btnRefreshHoaDon.Enabled = logic;
        }

        private void ResetTextboxInput()
        {
            txtGGKhach.Text = "";
            txtMaHD.Text = "";
            txtMaKH.Text = "";
            txtMaQT.Text = "";
            //txtNVTT.Text = "";
            txtTienKhach.Text = "";
            dtpkNgayIn.Value = dtpkNgayMua.Value = DateTime.Today;

            txtNVTT.ReadOnly = true;
            txtNVTT.Text = passData._account;
            txtMaHD.Text = AutoGenCode.GenNewCode("HoaDon");
        }


        private void btnUpdateHoaDon_Click(object sender, EventArgs e)
        {
            if (!searchClicked)
            {
                ResetTextboxInput();
                ButtonVisible(true);
                TextboxInputVisible(false);
            }
            else
            {
                txtGGKhach.Text = "";
                txtMaHD.Text = "";
                txtMaKH.Text = "";
                txtMaQT.Text = "";
                txtNVTT.Text = "";
                txtTienKhach.Text = "";
                dtpkNgayIn.Value = dtpkBD.MaxDate;
                dtpkNgayMua.Value = dtpkBD.MinDate;
                btnDetailsHoaDon.Enabled = btnPrint.Enabled = false;
            }
            DataView dv = new DataView(hdBAO.SelectAllHoaDon());
            dgvHoaDon.DataSource = dv;
        }

        private void btnThongKe_Click(object sender, EventArgs e)
        {
            if (!rdbHH.Checked && !rdbKH.Checked && !rdbNV.Checked && !rdbKM.Checked)
            {
                MessageBox.Show("Bạn phải chọn 1 trong các điều kiện lọc !");

            }
            else
            {

                DataSet dataSet = new DataSet();
                SqlCommand cmd;
                SqlDataAdapter da;
                DataTable dt;

                if (rdbNV.Checked)
                {
                    cmd = new SqlCommand("select * from dbo.fnc_ThongKeNV(@BD,@KT)", DataAccess.GetConnection());
                    //cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@BD", dtpkBD.Value);
                    cmd.Parameters.AddWithValue("@KT", dtpkKT.Value);
                    //cmd.ExecuteNonQuery();
                    da = new SqlDataAdapter(cmd);
                    dt = new DataTable();
                    da.Fill(dt);
                    dt.TableName = "Nhân viên";
                    dataSet.Tables.Add(dt);
                }


                bool flag = false;
                if (rdbHH.Checked)
                {
                    string loaiHang = "";
                    //for (int i = 0; i < cboLoaiHang.Items.Count; i++)
                    if (cboLoaiHang.Items.Contains(cboLoaiHang.Text))
                        flag = true;

                    if (flag == false)
                    {
                        MessageBox.Show("Bạn phải nhập giá trị từ các lựa chọn !");
                        cboLoaiHang.Focus();
                        return;
                    }

                    switch (cboLoaiHang.Text)
                    {
                        case "Tất cả":
                            loaiHang = "%";
                            break;
                        case "Thực phẩm":
                            loaiHang = "thuc pham";
                            break;
                        case "Gia dụng":
                            loaiHang = "gia dung";
                            break;
                        case "Điện tử":
                            loaiHang = "dien tu";
                            break;
                    }

                    cmd = new SqlCommand(String.Format("select * from dbo.fnc_ThongKeHang(@BD,@KT,'{0}')", loaiHang), DataAccess.GetConnection());
                    cmd.Parameters.AddWithValue("@BD", dtpkBD.Value);
                    cmd.Parameters.AddWithValue("@KT", dtpkKT.Value);
                    da = new SqlDataAdapter(cmd);
                    dt = new DataTable();
                    da.Fill(dt);
                    dt.TableName = "Hàng hóa";
                    dataSet.Tables.Add(dt);
                }


                if (rdbKH.Checked)
                {
                    flag = false;

                    //for (int i = 0; i < cboKH.Items.Count; i++)
                    if (cboKH.Items.Contains(cboKH.Text))
                        flag = true;
                    if (!flag)
                    {
                        MessageBox.Show("Bạn phải chọn 1 giá trị từ danh sách !");
                        cboKH.Focus();
                        return;
                    }

                    string loaiKH = "";
                    switch (cboKH.Text)
                    {
                        case "Tất cả":
                            loaiKH = "%";
                            break;
                        case "VIP":
                            loaiKH = "VIP";
                            break;
                        case "Thường":
                            loaiKH = "Thuong";
                            break;
                    }

                    cmd = new SqlCommand(String.Format("select * from dbo.fnc_ThongKeKH(@BD,@KT,'{0}')", loaiKH), DataAccess.GetConnection());
                    cmd.Parameters.AddWithValue("@BD", dtpkBD.Value);
                    cmd.Parameters.AddWithValue("@KT", dtpkKT.Value);
                    da = new SqlDataAdapter(cmd);
                    dt = new DataTable();
                    da.Fill(dt);
                    dt.TableName = "Khách hàng";
                    dataSet.Tables.Add(dt);
                }

                if (rdbKM.Checked)
                {

                    flag = false;

                    //for (int i = 0; i < cboKM.Items.Count; i++)
                    if (cboKM.Items.Contains(cboKM.Text))
                        flag = true;
                    if (!flag)
                    {
                        MessageBox.Show("Bạn phải chọn 1 giá trị từ danh sách !");
                        cboKM.Focus();
                        return;
                    }

                    string tenBang = "";
                    switch (cboKM.Text)
                    {
                        case "Tất cả":
                            tenBang = "All";
                            break;
                        case "Khách hàng":
                            tenBang = "GiamGiaKhach";
                            break;
                        case "Hàng hóa":
                            tenBang = "GiamGiaHang";
                            break;
                    }

                    if (tenBang != "All")
                    {
                        cmd = new SqlCommand(String.Format("select * from {0} where NgayKetThuc between @BD and @KT", tenBang), DataAccess.GetConnection());
                        cmd.Parameters.AddWithValue("@BD", dtpkBD.Value);
                        cmd.Parameters.AddWithValue("@KT", dtpkKT.Value);
                        da = new SqlDataAdapter(cmd);
                        dt = new DataTable();
                        da.Fill(dt);
                        dt.TableName = tenBang;
                        dataSet.Tables.Add(dt);
                    }
                    else
                    {
                        cmd = new SqlCommand(String.Format("select * from GiamGiaHang where NgayKetThuc between @BD and @KT"), DataAccess.GetConnection());
                        cmd.Parameters.AddWithValue("@BD", dtpkBD.Value);
                        cmd.Parameters.AddWithValue("@KT", dtpkKT.Value);
                        da = new SqlDataAdapter(cmd);
                        dt = new DataTable();
                        da.Fill(dt);
                        dt.TableName = "GiamGiaHang";
                        dataSet.Tables.Add(dt);

                        cmd = new SqlCommand(String.Format("select * from GiamGiaKhach where NgayKetThuc between @BD and @KT"), DataAccess.GetConnection());
                        cmd.Parameters.AddWithValue("@BD", dtpkBD.Value);
                        cmd.Parameters.AddWithValue("@KT", dtpkKT.Value);
                        da = new SqlDataAdapter(cmd);
                        dt = new DataTable();
                        da.Fill(dt);
                        dt.TableName = "GiamGiaKhach";
                        dataSet.Tables.Add(dt);
                    }
                }

                string filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                filePath += "\\Report_" + DateTime.Now.ToString().Replace('/', '_').Replace(':', '_') + ".xls";
                DialogResult dialog1 = MessageBox.Show("Báo cáo đang được xử lý, đợi trong giây lát");
                if (dialog1 == DialogResult.OK)
                {
                    InBaoCao(dataSet, filePath);
                    DialogResult dialog2 = MessageBox.Show("Báo cáo đã được xử lý xong !");
                    if (dialog2 == DialogResult.OK)
                    {
                        Microsoft.Office.Interop.Excel.Application _excel = new Microsoft.Office.Interop.Excel.Application();
                        Microsoft.Office.Interop.Excel.Workbook _wb = _excel.Workbooks.Open(filePath);
                        //openFileDialog1.FileName = filePath;
                        //openFileDialog1.OpenFile();
                    }
                }
            }
        }


        public void InBaoCao(DataSet dataSet, string filePath)
        {
            Microsoft.Office.Interop.Excel.ApplicationClass appClass = new Microsoft.Office.Interop.Excel.ApplicationClass();
            Microsoft.Office.Interop.Excel.Workbook workBook = appClass.Workbooks.Add(Type.Missing);

            int sheetIndex = 0;


            foreach (DataTable table in dataSet.Tables)
            {
                int startX = 2, startY = 2;
                Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Sheets.Add(
                    workBook.Sheets.get_Item(++sheetIndex),
                    Type.Missing, 1, Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);

                sheet.Name = table.TableName;

                sheet.Cells[startX, startY] = "BÁO CÁO THỐNG KÊ " + sheet.Name;
                startX += 2;
                startY += 2;
                sheet.Cells[startX, startY] = "Ngày bắt đầu thống kê:";
                sheet.Cells[startX, startY + 1] = dtpkBD.Value.ToString();
                sheet.Cells[startX + 1, startY] = "Ngày kết thúc thống kê:";
                sheet.Cells[startX + 1, startY + 1] = dtpkKT.Value.ToString();

                startY += 5;

                for (int i = 0; i < table.Columns.Count; i++)
                {
                    sheet.Cells[startY, i + startX] = table.Columns[i].ToString();
                }

                for (int i = 0; i < table.Rows.Count; i++)
                {
                    for (int j = 0; j < table.Columns.Count; j++)
                        sheet.Cells[i + 1 + startY, j + startX] = table.Rows[i].ItemArray[j].ToString();
                }
            }


            // Save and Close the Workbook
            workBook.SaveAs(filePath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing,
                Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            workBook.Close(true, Type.Missing, Type.Missing);
            workBook = null;

            // Release the Application object
            appClass.Quit();
            appClass = null;

            // Collect the unreferenced objects
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }

        private void rdbHH_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbHH.Checked)
                cboLoaiHang.Enabled = true;
            else
                cboLoaiHang.Enabled = false;
        }

        private void rdbKH_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbKH.Checked)
                cboKH.Enabled = true;
            else
                cboKH.Enabled = false;
        }


        static bool searchClicked = false;
        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (!searchClicked)
            {
                searchClicked = true;
                btnSearch.BackgroundImage = (Image)(Properties.Resources.ResourceManager.GetObject("TatTK"));
                txtGGKhach.Text = "";
                SearchMode(false);
                txtMaHD.Text = "";
                txtNVTT.Text = "";
                txtNVTT.ReadOnly = false;
                dtpkNgayMua.Value = dtpkBD.MinDate;
                dtpkNgayIn.Value = dtpkKT.MaxDate;
                lblNgay1.Text = "Từ ngày";
                lblNgay2.Text = "Đến ngày";
                btnRefreshHoaDon.Enabled = true;
            }
            else
            {
                //btnRefreshHoaDon.PerformClick();
                btnSearch.BackgroundImage = (Image)(Properties.Resources.ResourceManager.GetObject("BatTK"));
                SearchMode(true);
                searchClicked = false;
                this.ResetTextboxInput();
                lblNgay1.Text = "Ngày mua hàng";
                lblNgay2.Text = "Ngày in hóa đơn";
                //dgvHoaDon.DataSource = dvSearch;

                DataView dv = new DataView(hdBAO.SelectAllHoaDon());
                dgvHoaDon.DataSource = dv;
            }
        }

        private void SearchMode(bool logic)
        {
            ResetTextboxInput();
            TextboxInputVisible(logic);
            txtGGKhach.ReadOnly = logic;
            txtMaHD.ReadOnly = logic;
            ButtonVisible(logic);
            btnPrint.Enabled = false;
            btnDetailsHoaDon.Enabled = false;
        }


        List<string> listStringFilter = new List<string>();

        private string ToStringFilter(List<string> list)
        {
            string s = "";
            if (list.Count >= 2)
                for (int i = 0; i < list.Count - 1; i++)
                    s += list.ToArray()[i] + " AND ";
            if (list.Count >= 1)
                s += list.ToArray()[list.Count - 1];
            Console.WriteLine(s);
            return s;
        }
        private void FilterChanged(object sender, EventArgs e)
        {
            txtGGKhach.Text.ToUpper();
            if (searchClicked)
            {
                listStringFilter = new List<string>();
                //Console.WriteLine(txtNVTT.Text);
                listStringFilter.Add(String.Format("MaHoaDon like '{0}%'", txtMaHD.Text));
                listStringFilter.Add(String.Format("MaKhachHang like '{0}%'", txtMaKH.Text));
                listStringFilter.Add(String.Format(" convert(TienKhachDua,System.String) like '{0}%'", txtTienKhach.Text));
                listStringFilter.Add(String.Format("MaNVThanhToan like '{0}%'", txtNVTT.Text));
                listStringFilter.Add(String.Format("MaQT like '{0}%'", txtMaQT.Text));
                listStringFilter.Add(String.Format(" convert(MaGiamGiaKhach,System.String) like '{0}%'", txtGGKhach.Text));

                listStringFilter.Add(String.Format("(NgayMuaHang >= '{0}' and NgayMuaHang<= '{1}')", dtpkNgayMua.Value, dtpkNgayIn.Value));

                dvSearch.RowFilter = ToStringFilter(listStringFilter);
                dgvHoaDon.DataSource = dvSearch;
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            PrintDocument printDoc = new PrintDocument();
            printDialog.Document = printDoc;
            printDoc.DocumentName = "HoaDon_" + txtMaHD.Text + "_" + DateTime.Now.ToString();
            printDoc.PrintPage += printDoc_PrintPage;
            DialogResult result = printDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                printDoc.Print();
                if (!searchClicked)
                    btnRefreshHoaDon.PerformClick();
            }
        }


        public string BlankSpace(string s, int n)
        {
            string tmp = "";
            for (int i = 0; i < n; i++)
                tmp += s;
            return tmp;
        }

        ChiTietHoaDonBAO ctBAO = new ChiTietHoaDonBAO();

        private void printDoc_PrintPage(object sender, PrintPageEventArgs e)
        {

            PrintDocument printDoc = sender as PrintDocument;

            DataView dv = ctBAO.SelectViewChiTietHoaDon(txtMaHD.Text);

            Graphics graph = e.Graphics;
            Font font = new Font("Segoe UI", 9);
            SolidBrush textColor = new SolidBrush(Color.Magenta);


            SqlCommand cmd;
            SqlDataAdapter da;
            DataTable dt;
            int delta = 0;

            int[] jumpSpaces = { 0, 70, 220, 55, 50, 70, 70, 70 };



            int startX = 10;
            int startY = 10;
            int fontH = font.Height;

            graph.DrawString("HANDSOME Cash & Carry VietNam", new Font("Segoe UI", 20), new SolidBrush(Color.Black), new Point(startX, startY));

            startY += fontH * 4;
            graph.DrawString("Thông tin khách hàng:", font, textColor, new Point(startX + 450, startY));
            graph.DrawString("Thông tin hóa đơn:", font, textColor, new Point(startX, startY));
            startY += fontH;
            graph.DrawString(("Mã khách hàng:" + dv.Table.Rows[0]["MaKH"].ToString()), font, textColor, new Point(startX + 450, startY));
            graph.DrawString("Mã hoa đơn:" + dv.Table.Rows[0]["MaHoaDon"].ToString(), font, textColor, new Point(startX, startY));
            startY += fontH;
            graph.DrawString(("Tên khách hàng:" + dv.Table.Rows[0]["TenKH"].ToString()), font, textColor, new Point(startX + 450, startY));
            graph.DrawString("Ngày mua hang:" + dv.Table.Rows[0]["NgayMuaHang"].ToString(), font, textColor, new Point(startX, startY));
            startY += fontH;
            graph.DrawString("Ngày in hóa đơn:" + dv.Table.Rows[0]["NgayInHoaDon"].ToString(), font, textColor, new Point(startX, startY));


            startY += fontH * 4;

            cmd = new SqlCommand("Select MaHoaDon,MaNVThanhToan, MaQT,MaGiamGiaKhach from view_ChiTietHoaDon where MaHoaDon=@mahd", DataAccess.GetConnection());
            cmd.Parameters.AddWithValue("@mahd", txtMaHD.Text);
            da = new SqlDataAdapter(cmd);
            dt = new DataTable();
            da.Fill(dt);
            DataView dsCTNV = new DataView(dt);
            //dv.RowFilter = String.Format("MaHoaDon='{0}'", txtMaHD.Text);
            for (int i = 0; i < dsCTNV.Table.Columns.Count; i++)
            {
                graph.DrawString(dsCTNV.Table.Columns[i].ToString() + ":" + dsCTNV.Table.Rows[0].ItemArray[i].ToString(), font, textColor, new Point(startX + 150 * i, startY));
                if (i == dsCTNV.Table.Columns.Count - 1)
                    graph.DrawString("Trang" + ":" + (pageNum + 1).ToString(), font, textColor, new Point(startX + 150 * (i + 2), startY));

            }

            cmd = new SqlCommand("Select MaHang, TenHang,DonVi,SoLuongMua as SL,MaGiamGiaHang as MaGG," +
            "GiaTruocVAT as GiaGoc, VAT,ThanhTien from view_ChiTietHoaDon where MaHoaDon=@mahd", DataAccess.GetConnection());
            cmd.Parameters.AddWithValue("@mahd", txtMaHD.Text);
            da = new SqlDataAdapter(cmd);
            dt = new DataTable();
            da.Fill(dt);
            DataView dvDSHang = new DataView(dt);

            startY += fontH;
            graph.DrawString(BlankSpace("-", 200), font, textColor, new Point(startX, startY));
            startY += fontH;
            delta = 0;
            for (int i = 0; i < dvDSHang.Table.Columns.Count; i++)
            {
                delta += jumpSpaces[i];
                graph.DrawString(dvDSHang.Table.Columns[i].ToString(), font, new SolidBrush(Color.Magenta), new Point(startX + delta, startY));
            }
            startY += fontH;
            graph.DrawString(BlankSpace("-", 200), font, textColor, new Point(startX, startY));
            startY += fontH;



            for (int i = pageNum + pageNum * (RowPerPage - 1); i < (pageNum + 1) * RowPerPage; i++)
            {
                delta = 0;
                if (dvDSHang.Table.Rows.Count == i)
                    break;
                for (int j = 0; j < dvDSHang.Table.Columns.Count; j++)
                {
                    delta += jumpSpaces[j];
                    if (j != 1)
                        graph.DrawString(dvDSHang.Table.Rows[i].ItemArray[j].ToString(), font, textColor, new Point(startX + delta, startY));
                }
                graph.DrawString(dvDSHang.Table.Rows[i].ItemArray[1].ToString().Substring(0, Math.Min(30, dvDSHang.Table.Rows[i].ItemArray[1].ToString().Length)), font, textColor, new Point(startX + jumpSpaces[1], startY));
                sum += (int)Convert.ToDouble(dvDSHang.Table.Rows[i]["ThanhTien"].ToString());
                startY += fontH;
            }
            graph.DrawString(BlankSpace("-", 200), font, textColor, new Point(startX, startY));

            if (pageNum < Math.Round((double)dv.Table.Rows.Count / RowPerPage, 1) - 1)
            {
                pageNum += 1;
                e.HasMorePages = true;
            }
            else
            {
                startY += fontH;
                graph.DrawString("Tổng cộng:", font, textColor, new Point(startX, startY));
                delta = 0;
                for (int i = 0; i < jumpSpaces.Length; i++)
                    delta += jumpSpaces[i];
                graph.DrawString(sum.ToString(), font, textColor, new Point(startX + delta, startY));
                startY += fontH;
                graph.DrawString("Mã giảm giá khách:", font, textColor, new Point(startX, startY));


                graph.DrawString(dv.Table.Rows[0]["MaGiamGiaKhach"].ToString(), font, textColor, new Point(startX + delta, startY));
                startY += fontH;
                GiamGiaKHBAO ggkBAO = new GiamGiaKHBAO();
                graph.DrawString("Triết khấu cho khách(%):", font, textColor, new Point(startX, startY));

                if (dv.Table.Rows[0]["MaGiamGiaKhach"].ToString() != "0")
                {
                    graph.DrawString(ggkBAO.GiamGiaKH_LayChietKhau(dv.Table.Rows[0]["MaGiamGiaKhach"].ToString()).ToString(), font, textColor, new Point(startX + delta, startY));
                    chietKhau = ggkBAO.GiamGiaKH_LayChietKhau(dv.Table.Rows[0]["MaGiamGiaKhach"].ToString());
                }
                else
                    graph.DrawString("0", font, textColor, new Point(startX + delta, startY));
                startY += fontH;
                tienTra = (sum - sum * chietKhau / 100);
                graph.DrawString("Tổng cộng tiền của khách:", font, textColor, new Point(startX, startY));
                graph.DrawString(tienTra.ToString(), font, textColor, new Point(startX + delta, startY));

                startY += fontH;
                tienKhach = Convert.ToInt32(dv.Table.Rows[0]["TienKhachDua"].ToString());
                graph.DrawString("Tiền khách đưa:", font, textColor, new Point(startX, startY));
                graph.DrawString(dv.Table.Rows[0]["TienKhachDua"].ToString(), font, textColor, new Point(startX + delta, startY));

                startY += fontH;
                graph.DrawString(BlankSpace("-", 200), font, textColor, new Point(startX, startY));
                startY += fontH;
                graph.DrawString("Tiền gửi khách:", font, textColor, new Point(startX, startY));
                graph.DrawString((tienKhach - tienTra).ToString(), font, textColor, new Point(startX + delta, startY));
            }
        }

        private void rdbKM_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbKM.Checked)
                cboKM.Enabled = true;
            else
                cboKH.Enabled = false;
        }

        private void dgvHoaDon_SelectionChanged(object sender, EventArgs e)
        {
        }


    }
}
